/**
 * Copyright (c) 2015-2018, Golly Hu 胡高 (3722711@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.hg.jfsa.core.option;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;

/**
 * @author Golly
 */
public class Options {

	private static final List<OptionChangeListener> LISTENERS = new ArrayList<>();
	private static final Log LOG = Log.getLog(Options.class);
	private static final Map<String, Object> options = new ConcurrentHashMap<>();

	public static void addListener (OptionChangeListener listener) {

		if (Options.LISTENERS.contains(listener)) {
			return;
		}

		Options.LISTENERS.add(listener);
	}

	public static String get (String key) {
		return (String) Options.options.get(key);
	}

	public static Map<String, Object> getAll () { return Options.options; }

	public static boolean getAsBool (String key) {
		return Boolean.parseBoolean((String) Options.options.get(key));
	}

	public static float getFloat (String key, float defaultValue) {
		String value = Options.get(key);

		if (StrKit.isBlank(value)) {
			return defaultValue;
		}

		return Float.parseFloat(value);
	}

	public static int getInt (String key, int defaultValue) {
		String value = Options.get(key);

		if (StrKit.isBlank(value)) {
			return defaultValue;
		}

		return Integer.parseInt(value);
	}

	public static void removeListener (OptionChangeListener listener) {
		Options.LISTENERS.remove(listener);
	}

	public static void set (String key, String value) {

		if (StrKit.isBlank(key)) {
			return;
		}

		String oldValue = (String) Options.options.get(key);

		if (Objects.equals(value, oldValue)) {
			return;
		}

		Options.options.put(key, value);

		for (OptionChangeListener listener : Options.LISTENERS) {

			try {
				listener.onChanged(key, value, oldValue);
			}
			catch (Throwable ex) {
				Options.LOG.error(ex.toString(), ex);
			}

		}

	}

	public interface OptionChangeListener {

		void onChanged (String key, String newValue, String oldValue);

	}

}
